<template>
  <div class="news-review">
    <el-card class="filter-container">
      <div class="filter-header">
        <h2>新闻审核管理</h2>
        <div class="filter-options">
          <el-select v-model="filterStatus" placeholder="审核状态" clearable>
            <el-option label="待审核" value="pending" />
            <el-option label="已通过" value="approved" />
            <el-option label="已拒绝" value="rejected" />
          </el-select>
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetFilters">重置</el-button>
        </div>
      </div>
    </el-card>

    <el-card class="review-list">
      <el-table
        v-loading="loading"
        :data="reviewList"
        style="width: 100%"
        border
      >
        <el-table-column prop="contentId" label="内容ID" width="80" />
        <el-table-column label="新闻标题" min-width="200">
          <template #default="{ row }">
            <div class="news-info">
              <span class="news-title">{{ row.contentTitle }}</span>
              <el-button
                link
                @click="viewNewsContent(row)"
              >
                查看内容
              </el-button>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="reviewerName" label="审核人" width="120" />
        <el-table-column label="审核状态" width="100">
          <template #default="{ row }">
            <el-tag
              :type="getStatusType(row.reviewStatus)"
              effect="plain"
            >
              {{ getStatusText(row.reviewStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="reviewTime"
          label="提交审核时间"
          width="180"
          :formatter="formatDateTime"
        />
        <el-table-column prop="reviewComments" label="审核意见" min-width="200" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button
              v-if="row.reviewStatus === 'pending'"
              type="success"
              size="small"
              @click="handleReview(row, 'approved')"
            >
              通过
            </el-button>
            <el-button
              v-if="row.reviewStatus === 'pending'"
              type="danger"
              size="small"
              @click="handleReview(row, 'rejected')"
            >
              拒绝
            </el-button>
            <el-button
              v-if="row.reviewStatus !== 'pending'"
              type="primary"
              size="small"
              @click="viewReviewDetail(row)"
            >
              查看详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新闻内容查看对话框 -->
    <el-dialog
      v-model="newsDialogVisible"
      title="新闻内容"
      width="60%"
      destroy-on-close
    >
      <div v-if="selectedNews" class="news-detail">
        <h2>{{ selectedNews.title }}</h2>
        <div class="news-meta">
          <span>作者：{{ selectedNews.author }}</span>
          <span>发布时间：{{ formatDateTime(selectedNews.createDate) }}</span>
        </div>
        <div class="news-content" v-html="selectedNews.content"></div>
      </div>
    </el-dialog>

    <!-- 审核操作对话框 -->
    <el-dialog
      v-model="reviewDialogVisible"
      :title="reviewDialogTitle"
      width="500px"
      destroy-on-close
    >
      <el-form ref="reviewFormRef" :model="reviewForm" :rules="reviewRules">
        <el-form-item
          label="审核意见"
          prop="comments"
          :label-width="'100px'"
        >
          <el-input
            v-model="reviewForm.comments"
            type="textarea"
            :rows="4"
            placeholder="请输入审核意见"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="reviewDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitReview" :loading="submitting">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'

// 状态和数据
const loading = ref(false)
const submitting = ref(false)
const filterStatus = ref('')
const dateRange = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const reviewList = ref([])
const newsDialogVisible = ref(false)
const reviewDialogVisible = ref(false)
const selectedNews = ref(null)
const reviewDialogTitle = ref('')

// 审核表单
const reviewFormRef = ref()
const reviewForm = reactive({
  reviewId: null,
  contentId: null,
  status: '',
  comments: ''
})

// 表单验证规则
const reviewRules = {
  comments: [
    { required: true, message: '请输入审核意见', trigger: 'blur' },
    { min: 5, message: '审核意见不能少于5个字符', trigger: 'blur' }
  ]
}

// 获取审核列表
const fetchReviewList = async () => {
  loading.value = true
  try {
    const params = {
      page: currentPage.value,
      size: pageSize.value,
      status: filterStatus.value,
      startDate: dateRange.value?.[0],
      endDate: dateRange.value?.[1]
    }

    const response = await axios.get('/api/review/list', { params })
    reviewList.value = response.data.data.list
    total.value = response.data.data.total
  } catch (error) {
    console.error('获取审核列表失败:', error)
    ElMessage.error('获取审核列表失败')
  } finally {
    loading.value = false
  }
}

// 查看新闻内容
const viewNewsContent = async (row) => {
  try {
    const response = await axios.get(`/api/news/detail/${row.contentId}`)
    selectedNews.value = response.data.data
    newsDialogVisible.value = true
  } catch (error) {
    console.error('获取新闻内容失败:', error)
    ElMessage.error('获取新闻内容失败')
  }
}

// 处理审核操作
const handleReview = (row, status) => {
  reviewForm.reviewId = row.reviewId
  reviewForm.status = status
  reviewForm.comments = ''
  reviewForm.contentId = row.contentId
  reviewDialogTitle.value = status === 'approved' ? '通过审核' : '拒绝审核'
  reviewDialogVisible.value = true
}

// 提交审核
const submitReview = async () => {
  if (!reviewFormRef.value) return

  await reviewFormRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true
      try {
        await axios.post(`/api/review/${reviewForm.reviewId}`, {
          status: reviewForm.status,
          comments: reviewForm.comments,
          reviewerId: localStorage.getItem('id'),
          contentId: reviewForm.contentId
        })

        ElMessage.success('审核操作成功')
        reviewDialogVisible.value = false
        fetchReviewList()
      } catch (error) {
        console.error('审核操作失败:', error)
        ElMessage.error('审核操作失败')
      } finally {
        submitting.value = false
      }
    }
  })
}

// 查看审核详情
const viewReviewDetail = (row) => {
  ElMessageBox.alert(row.reviewComments, '审核详情', {
    confirmButtonText: '确定'
  })
}

// 处理查询
const handleSearch = () => {
  currentPage.value = 1
  fetchReviewList()
}

// 重置筛选条件
const resetFilters = () => {
  filterStatus.value = ''
  dateRange.value = []
  currentPage.value = 1
  fetchReviewList()
}

// 处理分页
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchReviewList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchReviewList()
}

// 格式化日期时间
const formatDateTime = (row, column, cellValue) => {
  if (!cellValue) return '-'
  const date = new Date(cellValue)
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
}

// 获取状态类型
const getStatusType = (status) => {
  const types = {
    pending: 'warning',
    approved: 'success',
    rejected: 'danger'
  }
  return types[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const texts = {
    pending: '待审核',
    approved: '已通过',
    rejected: '已拒绝'
  }
  return texts[status] || status
}

onMounted(() => {
  fetchReviewList()
})
</script>

<style scoped>
.news-review {
  padding: 20px;
}

.filter-container {
  margin-bottom: 20px;
}

.filter-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.filter-header h2 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
}

.filter-options {
  display: flex;
  gap: 15px;
  align-items: center;
}

.review-list {
  margin-bottom: 20px;
}

.news-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.news-title {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.news-detail {
  padding: 20px;
}

.news-detail h2 {
  margin: 0 0 20px 0;
  font-size: 24px;
  font-weight: 600;
}

.news-meta {
  margin-bottom: 20px;
  color: #666;
}

.news-meta span {
  margin-right: 20px;
}

.news-content {
  line-height: 1.8;
  font-size: 16px;
}

:deep(.el-dialog__body) {
  padding-top: 20px;
}
</style>
